package com.xr.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.xr.blog.exception.CustomException;
import com.xr.blog.exception.UserPasswordNotMatchException;
import com.xr.blog.service.LoginService;
import com.xr.blog.tools.IdUtils;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.constant.Code;
import com.xr.blog.tools.redis.RedisCache;
import com.xr.blog.tools.security.LoginBody;
import com.xr.blog.tools.security.LoginUser;
import com.xr.blog.tools.security.TokenService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.DecoderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    RedisCache redisCache;
    @Resource
    private AuthenticationManager authenticationManager;
    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    @Override
    public Result<String> login(LoginBody loginBody) throws NoSuchAlgorithmException, DecoderException, InvalidKeySpecException {
        //校验验证码
        String verifyKey = Code.CAPTCHA_CODE_KEY + loginBody.getUuid();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null){
            return Result.of(Code.VAILDATE_ERROR.getState(),"验证码已过期","验证码已过期");
        }
        if(!captcha.equalsIgnoreCase(loginBody.getCode())){
            return Result.of(Code.VAILDATE_ERROR.getState(),"验证码错误","验证码错误");
        }

        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                throw new UserPasswordNotMatchException();
            }
            else
            {
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return Result.of(Code.SC_OK.getState(),Code.SC_OK.getDescription(),tokenService.createToken(loginUser));
//        String token = IdUtils.fastUUID();
//        Map<String, Object> claims = new HashMap<>();
//        claims.put(Code.LOGIN_USER_KEY, token);
//        String token1 = Jwts.builder()
//                .setClaims(claims)
//                .signWith(SignatureAlgorithm.HS512, secret).compact();
//        System.out.println(token1);
        // 生成token
        //return Result.of(Code.SC_OK.getState(),Code.SC_OK.getDescription(),token1);
    }
}
